import React, { useState, useMemo } from "react";

// useMemo的作用和vue的计算属性是完全一样的
// 可以避免一些函数不必要的重新执行
const App = () => {
  const [count, setCount] = useState(1);
  const [num, setNum] = useState(10);
  const [list] = useState([1, 2, 3, 4, 5, 6, 7]);
  const [list2] = useState([
    {
      id: 1,
      name: "苹果",
      count: 10,
    },
    {
      id: 2,
      name: "香蕉",
      count: 5,
    },
    {
      id: 3,
      name: "菠萝",
      count: 8,
    },
  ]);

  const n = useMemo(() => {
    return list2.reduce((sum, item) => {
      return (sum += item.count);
    }, 0);
  }, [list2]);

  const oddList = useMemo(() => {
    return list.filter((item) => item % 2);
  }, [list]);

  const fn = useMemo(() => {
    console.log("fn函数被执行了");
    let sum = 0;
    for (let i = 0; i <= count * 100; i++) {
      sum += i;
    }
    return sum;
  }, [count]);

  return (
    <>
      <h2>useMemo</h2>
      <p>count: {count}</p>
      <button onClick={() => setCount((v) => v + 1)}>btn</button>
      <p>{fn}</p>

      <hr />

      <p>num: {num}</p>
      <button onClick={() => setNum((v) => v + 1)}>btn</button>

      <hr />
      <ul>
        {oddList.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>

      <hr />
      <p>总库存：{n}</p>
    </>
  );
};

export default App;
